package com.weaver.seconddev.api.tl.purchase_api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenkang.xu@weaver.cn
 * @create 2025-08-03 下午4:01
 * @Description
 */
@Slf4j
@org.springframework.stereotype.Service("tl_purchase_api_PlatformCommonService")
public class PlatformCommonService {



    /**
     * 按照upn,employeeId,id的顺序,只留靠前的1个作为查询条件，查询用户信息
     *
     * @param paramsList
     * @return
     */
    public static List<HrmResourceInfo> getUsersInfoBatch(List<HrmResourceInfo> paramsList) {
        log.info("======Start Query User Info Batch======");
        // 按照upn,employeeId,id的顺序,只留靠前的1个作为查询条件
        StringBuilder upnSb = new StringBuilder();
        StringBuilder employeeIdSb = new StringBuilder();
        StringBuilder idSb = new StringBuilder();
        for (HrmResourceInfo user : paramsList) {
            if (StringUtils.isNotBlank(user.getUpn())) {
                upnSb.append("'").append(user.getUpn()).append("',");
            } else if (StringUtils.isNotBlank(user.getEmployeeId())) {
                employeeIdSb.append("'").append(user.getEmployeeId()).append("',");
            } else if (user.getId() != null) {
                idSb.append(user.getId()).append(",");
            }
        }
        // 检查upn,employeeId,id是否全部为空
        if (upnSb.length() == 0 && employeeIdSb.length() == 0 && idSb.length() == 0) {
            return new ArrayList<HrmResourceInfo>();
        }
        // 查询用户信息
        String upnParameters = upnSb.toString();
        String employeeIdParameters = employeeIdSb.toString();
        String idParameters = idSb.toString();
        List<HrmResourceInfo> resultList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        if (StringUtils.isNotBlank(upnParameters)) {
            if (upnParameters.endsWith(",")) {
                upnParameters = upnParameters.substring(0, upnParameters.length() - 1);
            }
            // String sql = "select id,loginid,workcode,lastname from hrmresource where loginid in (" + upnParameters + ")";
            String sql = "SELECT hrmresource.id AS id, hrmresource.login_value AS loginid, hrmresource.job_num AS workcode, hrmresource.username AS lastname\n" +
                    "FROM (\n" +
                    "\tSELECT employee.*, user_info_login_param.login_value\n" +
                    "\tFROM eteams.employee\n" +
                    "\t\tLEFT JOIN eteams.user_info_login_param\n" +
                    "\t\tON user_info_login_param.login_type = 'loginName'\n" +
                    "\t\t\tAND employee.user_id = user_info_login_param.user_id\n" +
                    "\tWHERE employee.delete_type = 0\n" +
                    "\t\tAND employee.tenant_key = 'tl2k2r96ty'\n" +
                    ") hrmresource\n" +
                    "WHERE hrmresource.login_value IN (" + upnParameters + ")\n" +
                    "\tAND hrmresource.delete_type = 0\n" +
                    "\tAND hrmresource.tenant_key = 'tl2k2r96ty'";
            log.info("ExecuteSql:" + sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                HrmResourceInfo hrmResourceInfo = new HrmResourceInfo();
                hrmResourceInfo.setId(Util.getLongValue(rs.getString("id")));
                hrmResourceInfo.setUpn(rs.getString("loginid"));
                hrmResourceInfo.setEmployeeId(rs.getString("workcode"));
                hrmResourceInfo.setLastName(rs.getString("lastname"));
                resultList.add(hrmResourceInfo);
            }
        }
        if (StringUtils.isNotBlank(employeeIdParameters)) {
            if (employeeIdParameters.endsWith(",")) {
                employeeIdParameters = employeeIdParameters.substring(0, employeeIdParameters.length() - 1);
            }
            // String sql = "select id,loginid,workcode,lastname from hrmresource where workcode in (" + employeeIdParameters + ")";
            String sql = "SELECT hrmresource.id AS id, hrmresource.login_value AS loginid, hrmresource.job_num AS workcode, hrmresource.username AS lastname\n" +
                    "FROM (\n" +
                    "\tSELECT employee.*, user_info_login_param.login_value\n" +
                    "\tFROM eteams.employee\n" +
                    "\t\tLEFT JOIN eteams.user_info_login_param\n" +
                    "\t\tON user_info_login_param.login_type = 'loginName'\n" +
                    "\t\t\tAND employee.user_id = user_info_login_param.user_id\n" +
                    "\tWHERE employee.delete_type = 0\n" +
                    "\t\tAND employee.tenant_key = 'tl2k2r96ty'\n" +
                    ") hrmresource\n" +
                    "WHERE hrmresource.job_num IN ("+employeeIdParameters+")\n" +
                    "\tAND hrmresource.delete_type = 0\n" +
                    "\tAND hrmresource.tenant_key = 'tl2k2r96ty'";
            log.info("ExecuteSql:" + sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                HrmResourceInfo hrmResourceInfo = new HrmResourceInfo();
                hrmResourceInfo.setId(Util.getLongValue(rs.getString("id")));
                hrmResourceInfo.setUpn(rs.getString("loginid"));
                hrmResourceInfo.setEmployeeId(rs.getString("workcode"));
                hrmResourceInfo.setLastName(rs.getString("lastname"));
                resultList.add(hrmResourceInfo);
            }
        }
        if (StringUtils.isNotBlank(idParameters)) {
            if (idParameters.endsWith(",")) {
                idParameters = idParameters.substring(0, idParameters.length() - 1);
            }
            // String sql = "select id,loginid,workcode,lastname from hrmresource where id in (" + idParameters + ")";
            String sql = "SELECT hrmresource.id AS id, hrmresource.login_value AS loginid, hrmresource.job_num AS workcode, hrmresource.username AS lastname\n" +
                    "FROM (\n" +
                    "\tSELECT employee.*, user_info_login_param.login_value\n" +
                    "\tFROM eteams.employee\n" +
                    "\t\tLEFT JOIN eteams.user_info_login_param\n" +
                    "\t\tON user_info_login_param.login_type = 'loginName'\n" +
                    "\t\t\tAND employee.user_id = user_info_login_param.user_id\n" +
                    "\tWHERE employee.delete_type = 0\n" +
                    "\t\tAND employee.tenant_key = 'tl2k2r96ty'\n" +
                    ") hrmresource\n" +
                    "WHERE hrmresource.login_value IN (" + idParameters + ")\n" +
                    "\tAND hrmresource.delete_type = 0\n" +
                    "\tAND hrmresource.tenant_key = 'tl2k2r96ty'";
            log.info("ExecuteSql:" + sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                HrmResourceInfo hrmResourceInfo = new HrmResourceInfo();
                hrmResourceInfo.setId(Util.getLongValue(rs.getString("id")));
                hrmResourceInfo.setUpn(rs.getString("loginid"));
                hrmResourceInfo.setEmployeeId(rs.getString("workcode"));
                hrmResourceInfo.setLastName(rs.getString("lastname"));
                resultList.add(hrmResourceInfo);
            }
        }
        log.info("======Complete Query User Info Batch======Query Result:" + JSON.toJSONString(resultList, SerializerFeature.WriteMapNullValue));
        return resultList;
    }



    /**
     * 查询数据库中记录的第三方系统token
     *
     * @param tokenName
     * @return
     */
    public static String getThirdPartySystemToken(String tokenName) {
        String tokenValue = null;
        try {
            log.info(String.valueOf("======Start Query DataBase Third Party System Token Value======TokenName:" + tokenName));
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
           //String queryTokenSql = "select token_name,token_value from third_app_access_token where token_name = ?";
            // 缺少表
            String queryTokenSql = "SELECT third_app_access_token.token_name AS token_name, third_app_access_token.token_value AS token_value\n" +
                    "FROM e10_common.third_app_access_token\n" +
                    "WHERE third_app_access_token.token_name = ?\n" +
                    "\tAND third_app_access_token.delete_type = 0\n" +
                    "\tAND third_app_access_token.tenant_key = 'tl2k2r96ty'";
            log.info(String.valueOf("Execute Sql:" + queryTokenSql));
            String poolname_5s = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            rs.executeQuery(queryTokenSql, poolname_5s, tokenName);
            if (rs.next()) {
                tokenValue = rs.getString("token_value");
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        log.info(String.valueOf("======Complete Query DataBase Third Party System Token Value======TokenName:" + tokenName + ",TokenValue:" + tokenValue));
        return tokenValue;
    }


    /**
     * 插入或更新第三方系统token
     *
     * @param tokenName
     * @return
     */
    public static boolean insertOrUpdateThirdPartySystemToken(String tokenName, String tokenValue) {
        boolean updateResult = false;
        try {
            log.info(String.valueOf("======Start Update DataBase Third Party System Token Value======TokenName:" + tokenName + ",TokenValue:" + tokenValue));
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            //String updateTokenSql = "insert into third_app_access_token (token_name, token_value) values (?,?) on duplicate key update token_name = ?, token_value = ?";
            String updateTokenSql = "INSERT INTO e10_common.third_app_access_token (token_name, token_value) " +
                    "VALUES (?, ?) " +
                    "ON DUPLICATE KEY UPDATE third_app_access_token.token_name = ?, third_app_access_token.token_value = ?";
            log.info(String.valueOf("Execute Sql:" + updateTokenSql));
            String poolname_61 = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            updateResult = rs.executeUpdate(updateTokenSql, poolname_61, tokenName, tokenValue, tokenName, tokenValue);
        } catch (Exception e) {
            log.error(e.toString());
        }
        log.info(String.valueOf("======Complete Update DataBase Third Party System Token Value======UpdateResult:" + updateResult + ",TokenName:" + tokenName + ",TokenValue:" + tokenValue));
        return updateResult;
    }
}
